/**
 * Created by LXhan on 2017/11/15.
 */
var $;
var form;
var layer;
var itemArray = new Array();
var $trees;
var oldData;//老数据
layui.use(['jquery', 'form', 'layer','tree'], function () {
    $ = layui.jquery;
    form = layui.form;
    layer = layui.layer;

    //操作类型：add新增，edit修改，view查看
    var type = QueryUtils.GetQueryString("type");
    var id = QueryUtils.GetQueryString("id");
    // getRoomInfo(id,type);
    var buildingId = QueryUtils.GetQueryString("buildingId");
    $trees = layui.tree({
        elem: '#hydropower' //传入元素选择器
        ,check:"checkbox"
        , nodes: getTreeNodes(id,type, buildingId)
        , click: function (node) {
            // generateItem(node.id,node.name)
            // $("form").children().eq(1).find("div").eq(1).find("input").eq(0).val(node.name);
            // $("form").children().eq(1).find("div").eq(1).find("input").eq(1).val(node.id);
        }
    });

    form.on('submit(relate)',function (data) {
        data.field.type = type;
        data.field.ROOMID = id;
        data.field.oldData = oldData;
        var datas = $trees.getChecked();
        var ids = "";
        if(datas.length>0){
            $.each(datas,function (i,data) {
                if(i ==0){
                    ids = data.id;
                }else {
                    ids+=","+data.id;
                }
            })
        }else {
            // layer.msg('请至少关联一项');
            var i = parent.layer.getFrameIndex(window.name);
            parent.layer.close(i);
            return false;
        }
        // data.field.itemArray = JSON.stringify(itemArray);
        data.field.ids = ids;
        var tips;
        if(type == 'b938139a48ed4344a11a7180b48eede6'){
            tips = '确定要关联电表吗？';
        }else {
            tips = '确定要关联水表吗？';
        }
        layer.msg(tips, {
            time: 0
            , btn: ['确定', '取消']
            , shade: 0.3
            , yes: function (index) {
                layer.close(index);
                $.ajax({
                    url: '/room/relatehydropower',
                    data: data.field,
                    dataType: "json",
                    type: "post",
                    async: false,
                    success: function (res) {
                        if (res.errcode === "00") {
                            var i = parent.layer.getFrameIndex(window.name);
                            parent.layer.close(i);
                            parent.layer.msg("保存成功", {offset: '150px'});
                        } else if (res.errcode === "01") {
                            layer.msg(res.errmsg, function () {
                            });
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        console.error(XMLHttpRequest.status);
                        console.error(XMLHttpRequest.readyState);
                        console.error(textStatus);
                    }
                });
            }
        });
        return false;
    })

    //tree背景色修改
    $("body").on("mousedown",".layui-tree a cite",function(){
        $(".layui-tree a cite").css('color','black')
        $(this).css('color','red');
    })
});
function getTreeNodes(type, buildingId) {
    var nodes;
    $.ajax({
        type: "post",
        url: "/hydropower/findbypid",
        async: false,
        data: {
            buildingId: buildingId,
            type: type
        },
        success: function (rs) {
            nodes = rs.data;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
        }
    });
    return nodes;
}
function getTreeNodes(id,type, buildingId) {
    var nodes;
    $.ajax({
        type: "post",
        url: "/room/findRoomHydroTree",
        async: false,
        data: {
            id:id,
            buildingId: buildingId,
            type: type
        },
        success: function (rs) {
            nodes = rs.data;
            oldData = rs.oldData;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
        }
    });
    return nodes;
}
function getRoomInfo(id,type) {
    $.ajax({
        type: "post",
        url: "/room/findRoomByRoomId",
        async: false,
        data: {
            id:id,
            type:type
        },
        success: function (rs) {
            var data = rs.data;
            buildingId = data.BUILDING_ID;
//                $("form").children().eq(0).find("div").eq(0).find("input").val(data.ROOM_NAME);
            $("form").children().eq(0).find("div").find("input").val(data.ROOM_NUM);
           /* $("form").children().eq(1).find("div").eq(1).find("input").eq(0).val(data.CODE);
            $("form").children().eq(1).find("div").eq(1).find("input").eq(1).val(data.ID);*/
            initItemArray(rs.data.list);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
        }
    });
}

function removeItem(self) {
    changeItemArray($(self).parent().attr("value"),1);
    if($(".tree-info").children().length == 1){
        $(".tree-info").find(".tree-item").eq(0).attr("value",1);
        $(".tree-info").find(".tree-item").eq(0).find(".item-data").text("请在左侧选择要关联的水（电）表编号");
        $(".tree-info").find(".tree-item").eq(0).find(".item-icon").find("i").remove();
    }else {
        $(self).parent().remove();
    }
}
function generateItem(id,code) {
    if($(".tree-info").children().length == 1 && $(".tree-info").find(".tree-item").eq(0).attr("value") == 1){
        $(".tree-info").find(".tree-item").eq(0).attr("value",id);
        $(".tree-info").find(".tree-item").eq(0).find(".item-data").text(code);
        $(".tree-info").find(".tree-item").eq(0).find(".item-icon").append($("<i class='layui-icon'>&#x1006;</i>"));
    }else {
        $(".tree-item").removeClass("item-color");
        var isAdd = true;
        $(".tree-item").each(function () {
            if($(this).attr("value") == id){
                $(this).addClass("item-color");
                isAdd = false;
            }
        })
       if(isAdd){
           var item = $("<div class='tree-item item-color' value='"+id+"'></div>");
           var data = $("<div class='item-data'>"+code+"</div>");
           var icon = $("<div class='item-icon' onclick='removeItem(this)'><i class='layui-icon'>&#x1006;</i></div>")
           item.append(data);
           item.append(icon);
           $(".tree-info").append(item);
       }
    }
    changeItemArray(id,0);
}
function changeItemArray(id,type) {
    var isNew = true;
    for(var i=0;i<itemArray.length;i++){
        if(itemArray[i].codeId == id){
            itemArray[i].type = type;
            isNew = false;
        }
    }
    if(isNew){
        var obj = new Object();
        obj.codeId = id;
        obj.type = type;
        obj.isNew = 1;
        itemArray.push(obj);
    }
}
function initItemArray(datas) {
   $.each(datas,function (i,item) {
       var obj = new Object();
       obj.id = item.ID;
       obj.codeId = item.CODEID;
       obj.type = 0;
       obj.isNew = 0;
       itemArray.push(obj);
       generateItem(item.CODEID,item.CODE);
   })
}